package com.itany.shop.factory;

import com.itany.shop.exception.ObjectFactoryException;
import com.itany.shop.util.JDBCTemplate;
import com.itany.shop.util.ParamterUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author MissChen
 * @version 1.0
 * @date 2023 年12月20日 14:40
 */
public class ObjectFactory {
    private static Map<String, Object> objs;

    static {
        objs = new HashMap<>();
        BufferedReader br;
        try {
            br = new BufferedReader(new InputStreamReader(ObjectFactory.class.getClassLoader().getResourceAsStream("beans.properties")));
            String line = null;
            while ((line = br.readLine()) != null) {
                if (!ParamterUtil.isNull(line)) {
                    String[] arr = line.split("=");
                    String key = arr[0];
                    String value = arr[1];
                    objs.put(key, Class.forName(value).newInstance());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("ObjectFactory初始化失败");
        } catch (InstantiationException e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("ObjectFactory初始化失败");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("ObjectFactory初始化失败");
        }
    }

    public static Object getObject(String key) {
        Object obj = objs.get(key);
        if (null == obj) {
            throw new ObjectFactoryException("根据指定的" + key + "在配置文件中没有找到对应的配置");
        }
        return obj;
    }

    public static void main(String[] args) {
        JDBCTemplate jdbcTemplate = (JDBCTemplate) ObjectFactory.getObject("jdbc");
        System.out.println(jdbcTemplate);
    }

}
